1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import com.google.common.annotations.GwtCompatible;
20  
21  import java.io.Serializable;
22  import java.util.List;
23  
24  import javax.annotation.Nullable;
25  
26  /** An ordering that compares objects according to a given order. */
27  @GwtCompatible(serializable = true)
28  final class ExplicitOrdering<T> extends Ordering<T> implements Serializable {
29    final ImmutableMap<T, Integer> rankMap;
30  
31    ExplicitOrdering(List<T> valuesInOrder) {
32      this(buildRankMap(valuesInOrder));
33    }
34  
35    ExplicitOrdering(ImmutableMap<T, Integer> rankMap) {
36      this.rankMap = rankMap;
37    }
38  
39    @Override public int compare(T left, T right) {
40      return rank(left) - rank(right); // safe because both are nonnegative
41    }
42  
43    private int rank(T value) {
44      Integer rank = rankMap.get(value);
45      if (rank == null) {
46        throw new IncomparableValueException(value);
47      }
48      return rank;
49    }
50  
51    private static <T> ImmutableMap<T, Integer> buildRankMap(
52        List<T> valuesInOrder) {
53      ImmutableMap.Builder<T, Integer> builder = ImmutableMap.builder();
54      int rank = 0;
55      for (T value : valuesInOrder) {
56        builder.put(value, rank++);
57      }
58      return builder.build();
59    }
60  
61    @Override public boolean equals(@Nullable Object object) {
62      if (object instanceof ExplicitOrdering) {
63        ExplicitOrdering<?> that = (ExplicitOrdering<?>) object;
64        return this.rankMap.equals(that.rankMap);
65      }
66      return false;
67    }
68  
69    @Override public int hashCode() {
70      return rankMap.hashCode();
71    }
72  
73    @Override public String toString() {
74      return "Ordering.explicit(" + rankMap.keySet() + ")";
75    }
76  
77    private static final long serialVersionUID = 0;
78  }